package cn.itcast.interceptor;

import cn.itcast.utils.JwtUtils;
import cn.itcast.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        //判断token是否存在
        if (!StringUtils.hasLength(token)){
            //不存在
            log.info("我拦截了请求=============");
            response.setStatus(401);//401
            return false;
        }
        /*解析token*/
        try {
            Claims claims = JwtUtils.parseJWT(token);
            //可以获取资源
            Object name = claims.get("name");
            System.out.println("========================token - name="+name);

            Object id = claims.get("id");
            ThreadLocalUtils.set(id);
            //解析成功，放行
            return true;
        } catch (Exception e) {
            //设置响应状态码，直接返回
            log.info("我拦截了未登录请求=============");
            response.setStatus(401);//401
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //删除对应的id
        ThreadLocalUtils.remove();
    }
}
